// src/context/SysAuthContext.tsx
import React, { createContext, useState, useCallback } from 'react';
import {
    sysAuthService,
    type Role,
    type Authority,
    type CreateRoleInput,
    type UpdateRoleInput,
    type BindUserAuthorityInput,
    type BindUserRoleInput
} from '../api/service/SysAuthService.tsx';

// 定义上下文类型
interface SysAuthContextType {
    // 角色相关
    roles: Role[];
    loadingRoles: boolean;
    fetchRoles: () => Promise<void>;
    createRole: (input: CreateRoleInput) => Promise<boolean>;
    updateRole: (input: UpdateRoleInput) => Promise<boolean>;
    deleteRole: (id: string) => Promise<boolean>;

    // 权限相关
    authorities: Authority[];
    loadingAuthorities: boolean;
    fetchAuthorities: () => Promise<void>;

    // 用户绑定相关
    bindUserAuthorities: (input: BindUserAuthorityInput) => Promise<boolean>;
    bindUserRoles: (input: BindUserRoleInput) => Promise<boolean>;

    // 错误处理
    error: string | null;
    clearError: () => void;
}

// 创建上下文
const SysAuthContext = createContext<SysAuthContextType | undefined>(undefined);

// Provider 组件
export const SysAuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [roles, setRoles] = useState<Role[]>([]);
    const [authorities, setAuthorities] = useState<Authority[]>([]);
    const [loadingRoles, setLoadingRoles] = useState<boolean>(false);
    const [loadingAuthorities, setLoadingAuthorities] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);

    // 清除错误
    const clearError = useCallback(() => {
        setError(null);
    }, []);

    // 获取角色列表
    const fetchRoles = useCallback(async () => {
        setLoadingRoles(true);
        setError(null);
        try {
            const result = await sysAuthService.getRoles();
            setRoles(result);
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '获取角色列表失败';
            setError(errorMessage);
            console.error('获取角色列表失败:', err);
        } finally {
            setLoadingRoles(false);
        }
    }, []);

    // 创建角色
    const createRole = useCallback(async (input: CreateRoleInput): Promise<boolean> => {
        setLoadingRoles(true);
        setError(null);
        try {
            const result = await sysAuthService.createRole(input);
            setRoles(prev => [result, ...prev]); // 将新角色添加到列表开头
            return true;
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '创建角色失败';
            setError(errorMessage);
            console.error('创建角色失败:', err);
            return false;
        } finally {
            setLoadingRoles(false);
        }
    }, []);

    // 更新角色
    const updateRole = useCallback(async (input: UpdateRoleInput): Promise<boolean> => {
        setLoadingRoles(true);
        setError(null);
        try {
            const result = await sysAuthService.updateRole(input);
            setRoles(prev => prev.map(role => role.id === result.id ? result : role));
            return true;
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '更新角色失败';
            setError(errorMessage);
            console.error('更新角色失败:', err);
            return false;
        } finally {
            setLoadingRoles(false);
        }
    }, []);

    // 删除角色
    const deleteRole = useCallback(async (id: string): Promise<boolean> => {
        setLoadingRoles(true);
        setError(null);
        try {
            const result = await sysAuthService.deleteRole(id);
            if (result) {
                setRoles(prev => prev.filter(role => role.id !== id));
            }
            return result;
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '删除角色失败';
            setError(errorMessage);
            console.error('删除角色失败:', err);
            return false;
        } finally {
            setLoadingRoles(false);
        }
    }, []);

    // 获取权限列表
    const fetchAuthorities = useCallback(async () => {
        setLoadingAuthorities(true);
        setError(null);
        try {
            const result = await sysAuthService.getAuthorities();
            setAuthorities(result);
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '获取权限列表失败';
            setError(errorMessage);
            console.error('获取权限列表失败:', err);
        } finally {
            setLoadingAuthorities(false);
        }
    }, []);

    // 绑定用户权限
    const bindUserAuthorities = useCallback(async (input: BindUserAuthorityInput): Promise<boolean> => {
        setError(null);
        try {
            const result = await sysAuthService.bindUserAuthorities(input);
            return result;
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '绑定用户权限失败';
            setError(errorMessage);
            console.error('绑定用户权限失败:', err);
            return false;
        }
    }, []);

    // 绑定用户角色
    const bindUserRoles = useCallback(async (input: BindUserRoleInput): Promise<boolean> => {
        setError(null);
        try {
            const result = await sysAuthService.bindUserRoles(input);
            return result;
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '绑定用户角色失败';
            setError(errorMessage);
            console.error('绑定用户角色失败:', err);
            return false;
        }
    }, []);

    return (
        <SysAuthContext.Provider
            value={{
                // 角色相关
                roles,
                loadingRoles,
                fetchRoles,
                createRole,
                updateRole,
                deleteRole,

                // 权限相关
                authorities,
                loadingAuthorities,
                fetchAuthorities,

                // 用户绑定相关
                bindUserAuthorities,
                bindUserRoles,

                // 错误处理
                error,
                clearError
            }}
        >
            {children}
        </SysAuthContext.Provider>
    );
};


export default SysAuthContext;
